package controllers

import (
	"ErgoGo/internal/model/article"
	"ErgoGo/internal/model/conf"
	articlegenerate "ErgoGo/internal/pkg/articleGenerate"
	"ErgoGo/pkg/database"
	"ErgoGo/pkg/http/response"
	"html/template"

	"github.com/gin-gonic/gin"
)

func HistoryList(c *gin.Context) {
	records, pagination := article.Paginate(c, 10)

	// 获取所有栏目
	categories := conf.GetCategories()
	// 创建栏目ID到名称的映射
	categoryMap := make(map[string]string)
	for _, cat := range categories {
		categoryMap[cat.ID] = cat.Name
	}

	c.HTML(200, "history", gin.H{
		"title":       "历史记录",
		"records":     records,
		"start":       (pagination.CurrentPage-1)*pagination.PerPage + 1,
		"end":         pagination.CurrentPage * pagination.PerPage,
		"total":       pagination.TotalCount,
		"prevPage":    pagination.PrevPageURL,
		"nextPage":    pagination.NextPageURL,
		"showHeader":  true,
		"active":      "history",
		"categoryMap": categoryMap,
	})
}

func HistoryDetail(c *gin.Context) {
	id := c.Param("id")
	article := article.Get(id)

	// 创建一个新的变量来存储HTML内容
	htmlContent := template.HTML(article.Content)

	c.HTML(200, "history_detail", gin.H{
		"title":      "历史记录",
		"article":    article,
		"content":    htmlContent,
		"showHeader": true,
	})
}

func HistoryDelete(c *gin.Context) {
	id := c.Param("id")
	article.Delete(id)

	response.Success(c)
}

func PublishArticle(c *gin.Context) {
	id := c.Param("id")
	_article := article.Get(id)

	// 调用发布功能
	gen := articlegenerate.NewArticleGenerator()

	// 构造文章对象
	articleObj := articlegenerate.Article{
		Title:    _article.Title,
		Content:  _article.Content,
		Keywords: _article.Keywords,
		Status:   1,
		Category: _article.Category,
		TagIds:   _article.TagIds,
	}

	// 发布文章
	err := gen.PublishArticle(articleObj)
	if err != nil {
		response.Error(c, err, "发布失败")
		return
	}

	// 更新文章状态
	_article.Status = 1
	database.DB.Save(&_article)

	response.Success(c)
}

type BatchDeleteRequest struct {
	Ids []string `json:"ids" binding:"required"`
}

func HistoryBatchDelete(c *gin.Context) {
	var req BatchDeleteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, err, "无效的请求参数")
		return
	}

	if err := article.BatchDelete(req.Ids); err != nil {
		response.Error(c, err, "删除失败")
		return
	}

	response.Success(c)
}
